﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml;

namespace CreativeMinds.Umbraco.Installation {

	public class SQLPackage {
		private static class Keys {
			public const string Query = "Query";
			public const string Version = "Version";
			public const string Key = "Key";
		}

		private XmlNode node = null;
		private string key = String.Empty;
		private Version version = null;
		private string script = String.Empty;

		public SQLPackage(string content) {
			XmlDocument xml = new XmlDocument();
			xml.LoadXml(content);
			this.node = xml.SelectSingleNode(Keys.Query);
		}

		public SQLPackage(XmlNode node) {
			this.node = node;
		}

		public string Key {
			get {
				if (this.key == "") {
					this.key = node.Attributes.GetNamedItem(Keys.Key).Value;
				}
				return this.key;
			}
		}

		public Version Version {
			get {
				if (this.version == null) {
					this.version = new Version(node.Attributes.GetNamedItem(Keys.Version).Value);
				}
				return this.version;
			}
		}

		public string Script {
			get {
				if (this.script == String.Empty) {
					this.script = this.RemoveGOStatements(node.InnerText);
				}
				return this.script;
			}
		}

		protected string RemoveGOStatements(string sqlScript) {
			return Regex.Replace(sqlScript, @"(?m)^\s*GO\s*\d*\s*$", "");
		}
	}
}